﻿using APP.QUANLY.Common;
using HLVControl.Grid.Data;
using MetroUI.Forms;
using RMAS.DAL;
using Sys;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RMAS
{
    public partial class frmImportProduct : Form
    {
        ExecuteNHAPKHO exe = new ExecuteNHAPKHO();
        DM_PARTNERINFO_Provider _provNCC = new DM_PARTNERINFO_Provider();
        DM_MENU_Provider _provmenu = new DM_MENU_Provider();
        DM_GROUPMENU_Provider _provGrmenu = new DM_GROUPMENU_Provider();
        WAREHOUSE_PRODUCT_Provider _provware = new WAREHOUSE_PRODUCT_Provider();
        QT_IMPORTDETIAL_MENU_TEMP_Provider _provCTTemp = new QT_IMPORTDETIAL_MENU_TEMP_Provider();
        private string LoaiPhieu="NK_SP";
        public frmImportProduct(string _LoaiPhieu)
        {
            InitializeComponent();
            this.LoaiPhieu = _LoaiPhieu;
            LoadAll();
        }
        public frmImportProduct()
        {
            InitializeComponent();
            LoadAll();
        }

        private void LoadAll()
        {
            LoadData();
            LoadUI();
        }
        private void LoadUI()
        {
            LoadMacDinhUI();
            labMaPhieu.Text = exe.TaoMaPhieu(LoaiPhieu);
            LoadHoaDon(labMaPhieu.Text);
        }

        public void LoadData()
        {
            LoadToCmbNhaCungCap();
            LoadToPnlNhomHang();
            LoadDSMatHang("0");
        }
        private void LoadToCmbNhaCungCap()
        {
            try
            {

                DM_PARTNERINFOList list = _provNCC.GetAll(false);
                DataTable data = new DataTable();
                data.Columns.Add("Mã", typeof(int));
                data.Columns.Add("Nhà cung cấp", typeof(string));
                foreach (DM_PARTNERINFO obj in list)
                {
                    data.Rows.Add(obj.PartnerID, obj.Name);
                }
                cmbNCC.DataSource = data;
                cmbNCC.DisplayMember = "Nhà cung cấp";
                cmbNCC.ValueMember = "Mã";
                cmbNCC.ColumnWidths = "0,200";
                cmbNCC.SelectedIndex = -1;
                cmbNCC.Text = "";
            }
            catch
            {

            }
        }
        private void LoadToPnlNhomHang()
        {
            try
            {
                DM_GROUPMENUList list = _provGrmenu.GetAll();

                if (list == null) return;
                if (list.Count == 0) return;

                Screen scr = Screen.PrimaryScreen;
                int vitrix = 0;
                int vitriy = 5;
                int khoangcach = 10;
                int TinhKhoangCach = khoangcach * list.Count;
                int ChieuRong = (scr.WorkingArea.Width - 700 - TinhKhoangCach) / (list.Count + 1);
                if (ChieuRong >= 200) ChieuRong = 200;
                if (ChieuRong <= 100) ChieuRong = 100;
                int ChieuDai = pnlNhomHang.Height - 10;

                DM_MENUList listP = _provmenu.GetAll();
                if (listP == null) return;
                if (listP.Count == 0) return;

                //-----------------------------------
                Button btnTatCa = new Button();
                btnTatCa.BringToFront();
                btnTatCa.BackColor = Color.FromArgb(128, 255, 128);
                btnTatCa.FlatStyle = FlatStyle.Flat;
                btnTatCa.FlatAppearance.BorderColor = Color.FromArgb(51, 51, 51);
                btnTatCa.FlatAppearance.BorderSize = 1;
                btnTatCa.FlatAppearance.MouseDownBackColor = Color.FromArgb(128, 255, 128);
                btnTatCa.FlatAppearance.MouseOverBackColor = Color.FromArgb(128, 255, 128);
                btnTatCa.Font = new Font("Segoe UI", (float)8.75, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                btnTatCa.UseVisualStyleBackColor = false;
                btnTatCa.ForeColor = Color.FromArgb(51, 51, 51);
                btnTatCa.Height = ChieuDai;
                btnTatCa.Width = ChieuRong;
                btnTatCa.UseVisualStyleBackColor = false;
                btnTatCa.Name = "0";
                btnTatCa.Text = "Tất cả";
                btnTatCa.Tag = "0";

                btnTatCa.Location = new Point(vitrix + khoangcach, vitriy);
                vitrix += ChieuRong + khoangcach;

                pnlNhomHang.Controls.Add(btnTatCa);
                btnTatCa.Click += btnLmh_Click;
                //----------------------------------

                foreach (DM_GROUPMENU obj in list)
                {
                    DM_MENUList listPr = listP.FindListByGroupMenuID(obj.ID);
                    if (listPr != null && listPr.Count > 0)
                    {
                        Button btnLmh = new Button();
                        btnLmh.BringToFront();
                        btnLmh.BackColor = Color.White;
                        btnLmh.FlatStyle = FlatStyle.Flat;
                        btnLmh.FlatAppearance.BorderColor = Color.FromArgb(51, 51, 51);
                        btnLmh.FlatAppearance.BorderSize = 1;
                        btnLmh.FlatAppearance.MouseDownBackColor = Color.FromArgb(128, 255, 128);
                        btnLmh.FlatAppearance.MouseOverBackColor = Color.FromArgb(128, 255, 128);
                        btnLmh.Font = new Font("Segoe UI", (float)8.75, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        btnLmh.UseVisualStyleBackColor = false;
                        btnLmh.ForeColor = Color.FromArgb(51, 51, 51);
                        btnLmh.Height = ChieuDai;
                        btnLmh.Width = ChieuRong;
                        btnLmh.UseVisualStyleBackColor = false;
                        btnLmh.Name = obj.ID.ToString();
                        btnLmh.Text = obj.Name;
                        btnLmh.Tag = obj.ID;

                        btnLmh.Location = new Point(vitrix + khoangcach, vitriy);
                        vitrix += ChieuRong + khoangcach;

                        pnlNhomHang.Controls.Add(btnLmh);
                        btnLmh.Click += btnLmh_Click;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        void btnLmh_Click(object sender, EventArgs e)
        {
            try
            {
                Button btn = (Button)sender;
                foreach (Button b in pnlNhomHang.Controls)
                {
                    b.BackColor = Color.White;
                }

                btn.BackColor = Color.FromArgb(128, 255, 128);
                labMaNhomHang.Text = btn.Name;
                LoadDSMatHang(labMaNhomHang.Text);
            }
            catch { }
        }

        private void LoadMacDinhUI()
        {
            labUser.Text = StaticVar.CurrUSER.FullName;
            txtDienThoai.Text = "";
            txtDiaChi.Text = "";
            txtGhiChu.Text = "";
            numTongTien.Value = 0;
            numTienChi.Value = 0;
            numChietKhau.Value = 0;
            numTienChietKhau.Value = 0;
            numTienKM.Value = 0;
            numThanhToan.Value = 0;

            numTongTien.ResetText();
            numTienChi.ResetText();
            numChietKhau.ResetText();
            numTienChietKhau.ResetText();
            numTienKM.ResetText();
            numThanhToan.ResetText();

            labMaKho.Text = "";
            labMaNCC.Text = "";
            cmbNCC.Text = "";
            labMaNhomHang.Text = "0";
            labMaPhieu.Text = "";
            labMaChiTiet.Text = "0";
            txtTimKiem.Text = "";
            UIHelper.LoadFocus(txtTimKiem);
        }
        private void LoadDSMatHang(string MaNhom)
        {
            try
            {
                treeDanhMuc.Rows.Clear();
                DataTable data = null;

                data = exe.DSMathang(StaticVar.MaKho, MaNhom);

                if (data != null && data.Rows.Count > 0)
                {
                    int count = 1;
                    foreach (DataRow drow in data.Rows)
                    {
                        string ID = drow[0].ToString();
                        string IDCode = drow[1].ToString();
                        string Mame = drow[2].ToString();

                        Decimal SLTon = 0;
                        WAREHOUSE_PRODUCT objW = _provware.GetBy_WHID_PrID(StaticVar.MaKho,ID);
                        if (objW != null) SLTon = objW.FirstBalance;

                        string Unit = drow[3].ToString();
                        Decimal GiaNhap = Decimal.Parse(drow[4].ToString());

                        TreeListRow row = treeHoaDon.CreateRow();
                        row.Cells.Add(new TreeListCell(count));
                        row.Cells.Add(new TreeListCell(ID));
                        row.Cells.Add(new TreeListCell(IDCode));
                        row.Cells.Add(new TreeListCell(Mame));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}", SLTon)));
                        row.Cells.Add(new TreeListCell(Unit));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}", GiaNhap)));

                        treeDanhMuc.Rows.Add(row);
                        count++;
                    }
                }
                treeDanhMuc.Refresh();
                treeDanhMuc.RefreshGrouping();
            }
            catch
            { }
        }
        private void LoadHoaDon(string MaHoaDon)
        {
            try
            {
                treeHoaDon.Rows.Clear();
                DataTable data = exe.HoaDon(MaHoaDon);
                if (data != null && data.Rows.Count > 0)
                {
                    int count = 1;
                    foreach (DataRow drow in data.Rows)
                    {
                        TreeListRow row = treeHoaDon.CreateRow();
                        row.Cells.Add(new TreeListCell(count));
                        row.Cells.Add(new TreeListCell(drow[0].ToString()));
                        row.Cells.Add(new TreeListCell(drow[1].ToString()));
                        row.Cells.Add(new TreeListCell(drow[2].ToString()));
                        row.Cells.Add(new TreeListCell(drow[3].ToString()));
                        row.Cells.Add(new TreeListCell(drow[4].ToString()));
                        row.Cells.Add(new TreeListCell(drow[5].ToString()));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}", Decimal.Parse(drow[6].ToString()))));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}", Decimal.Parse(drow[7].ToString()))));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}", Decimal.Parse(drow[8].ToString()))));
                        row.Cells.Add(new TreeListCell(drow[9].ToString()));

                        treeHoaDon.Rows.Add(row);
                        count++;
                    }
                }
                treeHoaDon.Refresh();
                TinhTien(MaHoaDon);
            }
            catch
            { }
        }
        private void TinhTien(string MaHoaDon)
        {
            try 
            {
                bool OK = false;
                Decimal TongTien=0, TienKhuyenMai=0,ThanhTien = 0;

                OK = exe.TinhTien(MaHoaDon, out TongTien, out TienKhuyenMai, out ThanhTien);
                numTongTien.Value = TongTien;
                numTienKM.Value = TienKhuyenMai;

                numTienChietKhau.Value = TongTien * (numChietKhau.Value / 100);
                numThanhToan.Value = TongTien - numTienChietKhau.Value - TienKhuyenMai;

                if (numTongTien.Value == 0) numTongTien.ResetText();
                if (numTienKM.Value == 0) numTienKM.ResetText();
                if (numTienChietKhau.Value == 0) numTienChietKhau.ResetText();
            }
            catch { }
        }

        private void XoaPhieuTam(bool isThoat)
        {
            if (treeHoaDon.Rows.Count == 0)
            {
                MessageBox.Show("Hóa đơn này chưa có sản phẩm để xóa!!!");
                return;
            }
            if (labMaPhieu.Text == "")
            {
                MessageBox.Show("Hóa đơn này chưa được khởi tạo!!!");
                return;
            }
            bool KQ = false;
            KQ = exe.XoaPhieuTam(labMaPhieu.Text);
            if (!isThoat) if (KQ) MessageBox.Show(exe.ErrMsg);
            if (KQ)
            {
                LoadUI();
            }
        }
        private void XoaMatHang(string MaHoaDon)
        {
            bool KQ = false;
            string MaChiTiet;
            try
            {
                TreeListRow firstSelected = treeHoaDon.SelectedElements[0] as TreeListRow;
                string ID = firstSelected.Cells[2].Text;
                QT_IMPORTDETIAL_MENU_TEMP obj = _provCTTemp.GetBy_ID(ID);
                if (obj != null)
                {
                    MaChiTiet = obj.ID;
                }
                else
                {
                    MessageBox.Show("vui lòng chọn mặt hàng cần cập nhật!!!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (MaChiTiet == "")
                {
                    MessageBox.Show("Vui lòng chọn mặt hàng trong hóa đơn để xóa!");
                    return;
                }

                KQ = exe.XoaMatHang(MaChiTiet);
                if (KQ)
                {
                    MessageBox.Show("Xóa mặt hàng thành công!");
                    LoadHoaDon(MaHoaDon);
                }
                else
                {
                    MessageBox.Show("Xóa mặt hàng thất bại!");
                }
            }
            catch
            {
                MessageBox.Show("Vui lòng chọn mặt hàng cần xóa!");
            }

        }
        private void TaoPhieu(string MaHoaDon)
        {
            try
            {
                if (labMaNCC.Text == "")
                {
                    MessageBox.Show("Vui lòng chọn nhà cung cấp trước!!!");
                    return;
                }
                if (treeHoaDon.Rows.Count == 0)
                {
                    MessageBox.Show("Hóa đơn này chưa có sản phẩm để tạo phiếu!!!");
                    return;
                }
                if (labMaPhieu.Text == "")
                {
                    MessageBox.Show("Hóa đơn này chưa được khởi tạo!!!");
                    return;
                }
                bool KQ = false;
                KQ = exe.TaoPhieuNhap(labMaPhieu.Text, int.Parse(labMaNCC.Text), (double)numTongTien.Value, (double)numChietKhau.Value, (double)numTienChietKhau.Value, (double)numTienKM.Value, (double)numTienChi.Value);
                if (KQ)
                {
                    LoadUI();
                }
                MessageBox.Show(exe.ErrMsg);
            }
            catch { }
        }

        private void treeDanhMuc_DoubleClickElement(object sender, HLVControl.Grid.Events.TreeListElementEventArgs e)
        {
            try
            {
                if (labMaNCC.Text == "")
                {
                    MessageBox.Show("Vui lòng chọn nhà cung cấp trước!!!");
                    return;
                }
                TreeListRow firstSelected = treeDanhMuc.SelectedElements[0] as TreeListRow;
                string ID = firstSelected.Cells[1].Text;
                string TenDonVi = firstSelected.Cells[5].Text;

                DM_MENU obj = _provmenu.GetBy_PrID(ID);
                if (obj != null)
                {
                    frmBangTinh bangtinh = new frmBangTinh(obj);
                    if (bangtinh.ShowDialog() == DialogResult.OK)
                    {
                        //xu ly nghiep vu nhap hang.
                        bool OK = false;
                        string MaChiTiet = labMaPhieu.Text + "_" + obj.PrID;
                        OK = exe.XuLyNghiepVu(labMaPhieu.Text, LoaiPhieu, StaticVar.MaKho, StaticVar.MaKho, null, int.Parse(labMaNCC.Text), txtDiaChi.Text, txtDienThoai.Text, MaChiTiet, obj.PrID, (float)frmBangTinh.SLNhap, obj.PrPrice_Purchase, TenDonVi, (float)frmBangTinh.TienGiamGia, (float)numChietKhau.Value, (float)numTienChi.Value, txtGhiChu.Text, StaticVar.CurrUSER.UserName);
                        if (OK)
                        {
                            LoadHoaDon(labMaPhieu.Text);
                        }
                        //MessageBox.Show(frmBangTinh.SLNhap.ToString() + "_" + frmBangTinh.TienGiamGia.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("vui lòng chọn mặt hàng cần nhập!!!","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }
            }
            catch
            {

            }
        }
        private void treeHoaDon_DoubleClickElement(object sender, HLVControl.Grid.Events.TreeListElementEventArgs e)
        {
            try
            {
                TreeListRow firstSelected = treeHoaDon.SelectedElements[0] as TreeListRow;
                string ID = firstSelected.Cells[2].Text;
                QT_IMPORTDETIAL_MENU_TEMP obj = _provCTTemp.GetBy_ID(ID);
                if (obj != null)
                {
                    labMaChiTiet.Text = obj.ID;
                    DM_MENU objmenu = _provmenu.GetBy_PrID(obj.PrID);
                    if (objmenu != null)
                    {
                        frmBangTinh bangtinh = new frmBangTinh(objmenu);
                        if (bangtinh.ShowDialog() == DialogResult.OK)
                        {
                            //xu ly nghiep vu nhap hang.
                            MessageBox.Show(frmBangTinh.SLNhap.ToString() + "_" + frmBangTinh.TienGiamGia.ToString());
                        }
                    }
                }
                else
                {
                    MessageBox.Show("vui lòng chọn mặt hàng cần cập nhật!!!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch
            {

            }
        }
        private void treeHoaDon_AfterSelectionChange(object sender, HLVControl.Grid.Events.TreeListElementEventArgs e)
        {
            try
            {
                TreeListRow firstSelected = treeHoaDon.SelectedElements[0] as TreeListRow;
                string ID = firstSelected.Cells[2].Text;
                QT_IMPORTDETIAL_MENU_TEMP obj = _provCTTemp.GetBy_ID(ID);
                if (obj != null)
                {
                    labMaChiTiet.Text = obj.ID;
                }
                else
                {
                    MessageBox.Show("vui lòng chọn mặt hàng cần cập nhật!!!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch
            {

            }
        }
        private void cmbNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbNCC.SelectedIndex >= 0)
            {
                DataRowView drvData = (DataRowView)cmbNCC.SelectedItem;
                string Ma = drvData.Row.ItemArray[0].ToString();
                string Ten = drvData.Row.ItemArray[1].ToString();
                DM_PARTNERINFO obj = _provNCC.GetBy_PartnerID(int.Parse(Ma));
                if (obj == null) return;
                labMaNCC.Text = Ma;
                cmbNCC.Text = Ten;
                txtDienThoai.Text = obj.Phone;
                txtDiaChi.Text = obj.Address;
            }
        }

        private void txt_Enter(object sender, EventArgs e)
        {
            UIHelper.txt_Enter(sender, e);
        }
        private void txt_Leave(object sender, EventArgs e)
        {
            UIHelper.txt_Leave(sender, e);
        }
        private void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                //TextBox txt = sender as TextBox;
                //if (txt.Name == txtTen.Name)
                //    UIHelper.txt_KeyPress(sender, numTu0Den8, e);
                //if (txt.Name == numTu0Den8.Name)
                //    UIHelper.txt_KeyPress(sender, numTu8Den18, e);
                //if (txt.Name == numTu8Den18.Name)
                //    UIHelper.txt_KeyPress(sender, numTu18Den24, e);
                //if (txt.Name == numTu18Den24.Name)
                //    UIHelper.txt_KeyPress(sender, cmbKhuVuc, e);
                //if (txt.Name == cmbKhuVuc.Name)
                //    UIHelper.txt_KeyPress(sender, numSTT, e);
                //if (txt.Name == numSTT.Name)
                //    UIHelper.txt_KeyPress(sender, txtGhiChu, e);
                //if (txt.Name == txtGhiChu.Name)
                //    UIHelper.txt_KeyPress(sender, btnXacNhan, e);
                //if (txt.Name == txtTimKiem.Name)
                //    UIHelper.txt_KeyPress(sender, btnTimKiem, e);
            }
            catch { }
        }
        private void num_ValueChanged(object sender, EventArgs e)
        {
            TinhTien(labMaPhieu.Text);
        }

        private void btn_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            string thaotac = btn.Tag.ToString();
            switch (thaotac)
            {
                case "thoat":
                    if (treeHoaDon.Rows.Count > 0)
                    {
                        if (MessageBox.Show("Phiếu nhập này chưa được tạo.\nBạn có chắc muốn thoát không?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            XoaPhieuTam(true);
                        }
                        else return;
                    }
                    base.Close();
                    break;
                case"inhoadon":

                    break;
                case "nhapkho":
                    TaoPhieu(labMaPhieu.Text);
                    break;
                case "bonhap":
                    XoaMatHang(labMaPhieu.Text);
                    break;
                case "xoahoadon":
                    XoaPhieuTam(false);
                    break;
                case "timkiem":
                    SearchProvider.SmartSearch(treeDanhMuc, txtTimKiem.Text.Trim(), new List<string> { });
                    break;
            }
           
        }
    }
}
